package controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/CodeServlet")
public class CodeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public CodeServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//调用静态方法获取验证码
		String code = CreateCode.getCode();
		//在session中保存验证码
		request.getSession().setAttribute("code", code);
		//将字符串转化为图片，JavaSwing的部分知识
		//BufferedImage在内存中保存一个图片对象，参数分别是宽，高，类型
		BufferedImage bi = new BufferedImage(80, 30, BufferedImage.TYPE_INT_RGB);
		//生成画笔
		Graphics gra = bi.getGraphics();
		//修改画笔颜色
		gra.setColor(Color.white);
		//画实心方框(修改背景颜色)
		gra.fillRect(0, 0, 80, 30);
		Random random = new Random();
        // 循环产生干扰线
		for (int i = 0; i < 155; i++) {
		// 随机产生155条干扰线，使图象中的认证码不易被其它程序探测到
			gra.setColor(Color.lightGray);
		// 干扰线起点X坐标
			int x = random.nextInt(80);
			// 干扰线起点Y坐标
			int y = random.nextInt(30);
			// 干扰线终点X坐标
			int xl = random.nextInt(12);
			// 干扰线终点Y坐标
			int yl = random.nextInt(12);
		// 绘制干扰线
			gra.drawLine(x, y, x + xl, y + yl);
		}
		//修改画笔颜色，字体
		gra.setColor(Color.red);
		Font font = new Font("宋体", Font.BOLD, 20);
		gra.setFont(font);
		//将验证码画在图片上
		gra.drawString(code, 10, 22);
		

		gra.dispose();
		//将图片输出到客户端
		ImageIO.write(bi, "jpeg", response.getOutputStream());
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
